#include "baidu_cloud.h"
#include "http.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cjson/cJSON.h>

#define TOKEN_URL "https://aip.baidubce.com/oauth/2.0/token"
#define ASR_URL "https://vop.baidu.com/server_api"

char *baidu_get_access_token(const char *api_key, const char *secret_key) {
    char url[1024];
    snprintf(url, sizeof(url), "%s?grant_type=client_credentials&client_id=%s&client_secret=%s", TOKEN_URL, api_key, secret_key);

    char *response = http_get(url);
    if (!response) {
        fprintf(stderr, "Failed to get response for token request\n");
        return NULL;
    }

    cJSON *json = cJSON_Parse(response);
    if (!json) {
        fprintf(stderr, "Failed to parse JSON from token response\n");
        free(response);
        return NULL;
    }

    cJSON *token = cJSON_GetObjectItem(json, "access_token");
    if (!token || !cJSON_IsString(token)) {
        fprintf(stderr, "Access token not found in response\n");
        cJSON_Delete(json);
        free(response);
        return NULL;
    }

    char *access_token = strdup(token->valuestring);
    cJSON_Delete(json);
    free(response);
    return access_token;
}

char *extract_result(const char *response) {
    cJSON *json = cJSON_Parse(response);
    if (!json) {
        fprintf(stderr, "解析JSON失败\n");
        return NULL;
    }

    cJSON *result = cJSON_GetObjectItemCaseSensitive(json, "result");
    if (!cJSON_IsArray(result) || cJSON_GetArraySize(result) == 0) {
        cJSON_Delete(json);
        fprintf(stderr, "结果数组不存在或为空\n");
        return NULL;
    }

    // 提取第一个识别结果
    cJSON *first_result = cJSON_GetArrayItem(result, 0);
    if (!cJSON_IsString(first_result)) {
        cJSON_Delete(json);
        fprintf(stderr, "结果格式错误\n");
        return NULL;
    }

    char *recognition_result = strdup(first_result->valuestring);
    cJSON_Delete(json);
    return recognition_result;
}

char *baidu_recognize_speech(const char *filename, const char *token, long *response_code) {
    FILE *file = fopen(filename, "rb");
    if (!file) {
        perror("Failed to open file for reading");
        return NULL;
    }

    fseek(file, 0, SEEK_END);
    size_t size = ftell(file);
    rewind(file);

    char *data = malloc(size);
    if (!data) {
        fclose(file);
        fprintf(stderr, "Failed to allocate memory for audio data\n");
        return NULL;
    }

    fread(data, 1, size, file);
    fclose(file);

    char url[1024];
    snprintf(url, sizeof(url), "%s?token=%s&cuid=7smartspeaker&dev_pid=1536", ASR_URL, token);

    char *response = http_post(url, data, size, response_code, "audio/pcm; rate=16000");
    free(data);
    return response;
}
